#pragma once
#include <iostream>
#include <sys/types.h>
#include <unistd.h>

#define TASKNUM 3

typedef void (*task_t)();
void Write()
{
    std::cout << "I am a write task" << std::endl;
}
void Flush()
{
    std::cout << "I am a flush task" << std::endl;
}
void Read()
{
    std::cout << "I am a read task" << std::endl;
}

task_t task[TASKNUM];
void LoadTask()
{
    srand(time(nullptr) ^ getpid()); //种下一个随机数种子,为挑选任务做准备
    task[0] = Write;
    task[1] = Flush;
    task[2] = Read;
}

void ExcuteTask(int num)
{
    if (num < 0 || num > 2)
        exit(1);
    task[num]();
}

int SelectTask()
{
    return rand()%TASKNUM;
}

void work()
{
    while (true)
    {
        int taskcommand = 0;
        int r = read(0, &taskcommand, sizeof(int));
        if (r == sizeof(int))
        {
            std::cout << "pid is : " << getpid() << " handler task" << std::endl;
            ExcuteTask(taskcommand);
        }
        else if (r == 0)
        {
            std::cout << "SubProcess:" << getpid() << " quit" << std::endl;
            break;
        }
    }
}